import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';

class Jdfpassportlogin {
  static const MethodChannel _channel = MethodChannel('jdfpassportlogin');

  ///
  /// 初始化必要参数
  ///
  /// cmAppId cmAppKey    //移动
  /// ctAppId ctAppKey   //联通
  /// cuAppId cuAppKey   //电信
  static Future<void> init({
    required int? appid,
    required int? develop,
    bool isLoginSwith = true,
    String? cmAppId,
    String? cmAppKey,
    String? ctAppId,
    String? ctAppKey,
    String? cuAppId,
    String? cuAppKey,
  }) async {
    _channel.invokeMethod(
      'init',
      {
        'appid': appid,
        'develop': develop,
        'isLoginSwith': isLoginSwith,
        'onKeyInfo': {
          'cmAppId': cmAppId,
          'cmAppKey': cmAppKey,
          'ctAppId': ctAppId,
          'ctAppKey': ctAppKey,
          'cuAppId': cuAppId,
          'cuAppKey': cuAppKey,
        }
      },
    );
  }

  ///账号密码登录
  static Future<void> loginWithAccountPassword({
    required String? account,
    required String? password,
    LoginCallBack? callBack,
  }) async {
    _channel.invokeMethod('loginWithAccountPassword', {
      'account': account,
      'password': password,
    }).then(
      (val) {
        if (null != callBack && null != val) {
          var result = jsonDecode(val);
          callBack.onLoginSuccess(
            LoginInfo()
              ..pin = result['pin']
              ..a2 = result['a2'],
          );
        } else {
          callBack?.onLoginFail("返回结果为空");
        }
      },
      onError: (e) {
        if (null != callBack) {
          if (e is PlatformException) {
            callBack.onLoginFail(e.message ?? "登录失败");
          }
        }
      },
    );
  }

  ///发送验证码
  static Future<void> sendVerifyCode({
    required String? phone,
    SendVerifyCodeCallBack? callBack,
  }) async {
    _channel.invokeMethod('sendVerifyCode', {'phone': phone}).then(
      (val) {
        if (null != callBack && null != val) {
          callBack.onSendVerifyCodeSuccess(val);
        } else {
          callBack?.onSendVerifyCodeFail("返回结果为空");
        }
      },
      onError: (e) {
        if (null != callBack) {
          if (e is PlatformException) {
            callBack.onSendVerifyCodeFail(e.message ?? "验证码发送失败");
          }
        }
      },
    );
  }

  ///验证码登录
  static Future<void> loginWithVerifyCode({
    required String? phone,
    required String? verifycode,
    LoginCallBack? callBack,
  }) async {
    _channel.invokeMethod('loginWithVerifyCode', {
      'phone': phone,
      'verifycode': verifycode,
    }).then(
      (val) {
        if (null != callBack && null != val) {
          var result = jsonDecode(val);
          callBack.onLoginSuccess(
            LoginInfo()
              ..pin = result['pin']
              ..a2 = result['a2'],
          );
        } else {
          callBack?.onLoginFail("返回结果为空");
        }
      },
      onError: (e) {
        if (null != callBack) {
          if (e is PlatformException) {
            callBack.onLoginFail(e.message ?? "验证码登录失败");
          }
        }
      },
    );
  }

  ///忘记密码
  static Future<void> forgetPassword() async {
    _channel.invokeMethod('forgetPassword');
  }

  ///获取版本号
  static Future<void> getAppVersion(void Function(String ver) callBack) async {
    if (Platform.isIOS) {
      callBack("2.0.0");
    } else {
      _channel.invokeMethod("getAppVersion").then((ver) {
        callBack(ver);
      });
    }
  }

  ///JD授权登录
  static Future<void> loginWithJD({LoginCallBack? callBack}) async {
    _channel.invokeMethod('loginWithJD').then(
      (val) {
        if (null != callBack && null != val) {
          var result = jsonDecode(val);
          callBack.onLoginSuccess(
            LoginInfo()
              ..pin = result['pin']
              ..a2 = result['a2'],
          );
        } else {
          callBack?.onLoginFail("返回结果为空");
        }
      },
      onError: (e) {
        if (null != callBack) {
          if (e is PlatformException) {
            callBack.onLoginFail(e.message ?? "京东的登录失败");
          }
        }
      },
    );
  }

  ///微信授权登录
  static Future<void> loginWithWx({
    required String? weixinId,
    LoginCallBack? callBack,
  }) async {
    _channel.invokeMethod('loginWithWx', {'weixinId': weixinId}).then(
      (val) {
        if (null != callBack && val != null) {
          var result = jsonDecode(val);
          callBack.onLoginSuccess(
            LoginInfo()
              ..pin = result['pin']
              ..a2 = result['a2'],
          );
        } else {
          callBack?.onLoginFail("返回结果为空");
        }
      },
      onError: (e) {
        if (null != callBack) {
          if (e is PlatformException) {
            callBack.onLoginFail(e.message ?? "微信登录失败");
          }
        }
      },
    );
  }

  ///
  /// 预取号：调用一键登录SDK方法获取安全手机号
  ///
  /// 说明：这个方法可以获取到手机号，用在一键登录页面展示手机号码。在app启动时调用，尽量靠前，否则可能进入登录页面后没有返回数据会导致页面无法展示手机号。
  ///
  static Future<void> oneKeyLoginPreGetMobile({
    OneKeyLoginPreCallBack? callBack,
  }) async {
    MethodChannel tmpChannel = _channel;
    tmpChannel.invokeMethod('oneKeyLoginPreGetMobile').then(
      (val) {
        if (null != callBack && null != val) {
          callBack.onOneKeyLoginPreSuccess("$val");
        } else {
          callBack?.onOneKeyLoginPreFail("返回结果为空");
        }
      },
      onError: (e) {
        if (null != callBack) {
          if (e is PlatformException) {
            callBack.onOneKeyLoginPreFail(e.message ?? "获取手机号失败");
          }
        }
      },
    );
  }

  ///运营商一键登录（移动、联通、电信）
  static Future<void> oneKeyLoginWithOperator({
    required String? securityPhone,
    LoginCallBack? callBack,
  }) async {
    assert(securityPhone != null);
    MethodChannel tmpChannel = _channel;
    tmpChannel.invokeMethod('oneKeyLoginWithOperator', {
      'securityPhone': securityPhone,
    }).then(
      (val) {
        if (null != callBack && null != val) {
          var result = jsonDecode(val);
          callBack.onLoginSuccess(
            LoginInfo()
              ..pin = result['pin']
              ..a2 = result['a2'],
          );
        } else {
          callBack?.onLoginFail("返回结果为空");
        }
      },
      onError: (e) {
        if (null != callBack) {
          if (e is PlatformException) {
            callBack.onLoginFail(e.message ?? "运营商一键登录失败");
          }
        }
      },
    );
  }
}

///发送验证码回调
abstract class SendVerifyCodeCallBack {
  void onSendVerifyCodeSuccess(int seconds);

  void onSendVerifyCodeFail(String error);
}

///登录回调
abstract class LoginCallBack {
  void onLoginSuccess(LoginInfo loginInfo);

  void onLoginFail(String error);
}

///运营商一键登录获取手机号
abstract class OneKeyLoginPreCallBack {
  void onOneKeyLoginPreSuccess(String mobile);

  void onOneKeyLoginPreFail(String error);
}

class LoginInfo {
  String? pin;
  String? a2;

  LoginInfo();

  LoginInfo.fromJson(Map<String, dynamic> json)
      : pin = json['pin'],
        a2 = json['a2'];
}

///开发环境
class DevelopType {
  ///PRODUCT 生成环境
  static final int product = 0;

  ///DEBUG 开发
  static final int debug = 1;

  ///BETA 预发
  static final int beta = 2;
}
